const app = getApp();
import {
  orderList, // 订单列表
  orderSend, // 确认发货
  orderSendUpdate,
} from "../../../../service/jb_oa_service"
import {
  queryOrderDetail
} from "../../../../service/jb_order_service"
import debounce from "../../../../tools/debounce"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentOrderData:null,//当前订单的详细信息
    showReceivePop:false,
    orderStatusOptions: [
      {
        text: "订单状态",
        value: "all"
      },
      {
        text: "未支付",
        value: "unPaid"
      },
      {
        text: "未发货",
        value: "notShipped"
      },
      {
        text: "待收货",
        value: "spike"
      },
      {
        text: "待评价",
        value: "bargain"
      },
      {
        text: "交易完成",
        value: "complete"
      },
      {
        text: "待核销",
        value: "toBeWrittenOff"
      },
      {
        text: "退款中",
        value: "refunding"
      },
      {
        text: "已退款",
        value: "refunded"
      },
      {
        text: "已删除",
        value: "deleted"
      },

    ],
    timeOptions: [
      {
        text: "时间筛选",
        value: ""
      },
      {
        text: "今天",
        value: "today"
      },
      {
        text: "昨天",
        value: "yesterday"
      },
      {
        text: "最近7天",
        value: "lately7"
      },
      {
        text: "最近30天",
        value: "lately30"
      },
      {
        text: "本月",
        value: "month"
      },
      {
        text: "本年",
        value: "year"
      },
    ],
    requestParams: {
      status: "all",
      dateLimit: "",
      orderNo: "",
      page: 1,
      limit: 20,
      type: 2,
    },
    dropDateLimit: "",
    orderList: [

    ],
    isShowLoading: false,//加载状态出现
    isBottomShow: false,//是否没有更多数据了
    showSendPop: false,//发送货弹窗
    sendType: 0, //0发货，1，送货，2，虚拟
    sendFormData: {
      id: '', //订单id
      orderNo: "",//订单编号
      type: 1,//发货类型 1：发货 2：送货，3:虚拟
      expressName: "",//快递公司
      expressCode: "",//快递公司编码
      expressNumber: "",//快递单号
      deliveryName: '',//送货人姓名
      deliveryTel: "",//送货人电话
      expressRecordType: 1,
    },
    singlePopTitle: "选择",
    showSinglePop: false,
    singlePopType: "",
    refreshFlag: false,
    currentOrderIndex: 0,
    isSendStatus:0,//0:第一次发送 1:修改发货信息
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getOrderList('refresh');
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  //时间筛选回调
  timeConfirmAction(e) {
    console.log("JJLog:结果是:" + JSON.stringify(e));
    // {"type":"timeConfirmAction","timeStamp":34363,"target":{"id":"","dataset":{}},"currentTarget":{"id":"","dataset":{}},"mark":{},"detail":{"showTimeText":"2022-10-05 - 2022-10-12","startTimeStr":"2022-10-05 00:00:00","endTimeStr":"2022-10-12 23:59:59"},"mut":false}
    if (e.detail.startTimeStr == '') {
      this.setData({
        'requestParams.dateLimit': '',
        dropDateLimit: '',
        'requestParams.page': 1,
        isBottomShow: false
      })
      this.getOrderList("refresh");
      return;
    }
    let startAt = e.detail.startTimeStr.split(' ')[0];
    let endAt = e.detail.endTimeStr.split(' ')[0];
    this.setData({
      'requestParams.dateLimit': startAt + "," + endAt,
      dropDateLimit: '',
      'requestParams.page': 1,
      isBottomShow: false
    })
    this.getOrderList("refresh");
    // console.log('JJLog:最终时间：' + this.data.requestParams.dateLimit)
  },

  //发送货
  sendProductAction(e) {
    console.log("JJLog:发送货：" + JSON.stringify(e));
    let orderData = e.detail;
    let index = e.currentTarget.dataset.index;
    this.setData({
      'sendFormData.orderNo': orderData.orderId,
      showSendPop: true,
      currentOrderIndex: index,
      isSendStatus:0,
    })
  },
  //查看收货信息
  seeReceiveAction(e) {
    if(this.data.currentOrderData && this.data.currentOrderData.orderId == e.detail.orderId){
      //点击到同一个了，就直接展示：
      this.setData({
        showReceivePop:true,
      })
      return;
    }
    this.queryOrderDetail(e.detail.orderId,'show');
  },
  clickCenterPopupOverlay() {
    this.setData({
      showSendPop: false,
      showReceivePop:false
    })
  },
  changeSendType(e) {
    let index = e.currentTarget.dataset.index;
    let type = index == 0 ? 1 : (index == 1 ? 2 : 3)


    this.setData({
      'sendFormData.type': type,
      sendType: index,
    })

  },

  //输入框回调
  cellInputChange(e) {
    console.log(JSON.stringify(e));
    let key = e.currentTarget.dataset.key;
    if (key == 'expressNumber') {
      this.setData({
        'sendFormData.expressNumber': e.detail.value
      })
    } else if (key == 'deliveryName') {
      this.setData({
        'sendFormData.deliveryName': e.detail.value
      })
    } else if (key == 'deliveryTel') {
      this.setData({
        'sendFormData.deliveryTel': e.detail.value
      })
    }

  },
  singlePopHide() {
    this.setData({
      showSinglePop: false,
    })
  },
  showSelectAction(e) {
    let key = e.currentTarget.dataset.key;
    if (key == "expressName") {
      this.setData({
        singlePopTitle: "选择物流公司",
        showSinglePop: true,
        singlePopType: "expressName"
      })
    }
  },
  //单选回调
  singlePopSelectCallback(e) {
    console.log(JSON.stringify(e));
    let detail = e.detail.result;
    this.setData({
      'sendFormData.expressName': detail.label,//取值就取value
      'sendFormData.expressCode': detail.value,
      showSinglePop: false,
    })
  },

  //下拉筛选状态变化
  dropdownMenuChange(e) {
    console.log("JJLog:哈哈哈哈：" + JSON.stringify(e));
    this.setData({
      'requestParams.status': e.detail,
      'requestParams.page': 1,
      isBottomShow: false,
    })
    this.getOrderList('refresh')
  },
  //下拉时间变化
  dropdownMenuTimeChange(e) {
    this.setData({
      'requestParams.dateLimit': e.detail,
      'requestParams.page': 1,
      dropDateLimit: e.detail,
      isBottomShow: false,
    })
    this.getOrderList('refresh')
  },
  //获取订单列表
  getOrderList(type) {
    wx.showLoading();
    orderList(this.data.requestParams).then(res => {
      wx.hideLoading();
      if (res.code == 200 && res.data) {
        let arr = (type == 'refresh' ? [] : this.data.orderList || []);
        arr = arr.concat(res.data.list || [])
        this.setData({
          orderList: arr,
          refreshFlag: false,
          isShowLoading: false,
          isBottomShow: res.data.totalPage == this.data.requestParams.page ? true : false,
        })
      }
    }).catch(err => {
      wx.hideLoading();

      wx.showToast({
        title: err || '加载失败',
        icon: "none"
      })
      if (this.data.requestParams.page != 1) {
        this.setData({
          'requestParams.page': this.data.requestParams.page - 1
        })
      }
      this.setData({
        refreshFlag: false,
      })
      console.error("JJLog:orderList", err);
    })
  },
  //修改物流信息
  changeExpressAction(e) {
    // wx.showToast({
    //   title: '开发中，请稍等',
    //   icon: "none"
    // })
    console.log("JJLog:发送货：" + JSON.stringify(e));
    let orderData = e.detail;
    let index = e.currentTarget.dataset.index;
    this.setData({
      'sendFormData.orderNo': orderData.orderId,
      showSendPop: true,
      currentOrderIndex: index,
      isSendStatus:1,
    })
  },
  // 刷新数据
  handleRefresh() {
    this.setData({
      'requestParams.page': 1,
      'requestParams.status': 'all',
      'requestParams.dateLimit': "",
      isBottomShow: false,
      refreshFlag: true,
    })
    this.getOrderList('refresh');
  },
  handleLoadmore() {
    if (this.data.isBottomShow) {
      return;
    }
    this.setData({
      isShowLoading: true,
      page: this.data.page + 1
    })
    this.getOrderList('')
  },
  sureSendOrderAction() {
    if (this.data.sendFormData.type == 1) {
      //快递公司发货：
      if (!this.data.sendFormData.expressName) {
        wx.showToast({
          title: '请选择快递公司',
          icon: "none"
        })
        return;
      }
      if (!this.data.sendFormData.expressNumber) {
        wx.showToast({
          title: '请填写快递单号',
          icon: "none"
        })
        return;
      }
      this.setData({
        'sendFormData.deliveryName': '',
        'sendFormData.deliveryTel': "",
      })
      if(this.data.isSendStatus == 0){
        debounce(this.sureSendOrder)
      }else{
        debounce(this.sureChangeOrder)
      }
      
    }
    if (this.data.sendFormData.type == 2) {
      //送货人送货：
      if (!this.data.sendFormData.deliveryName) {
        wx.showToast({
          title: '请填写送货人姓名',
          icon: "none"
        })
        return;
      }
      if (!this.data.sendFormData.deliveryTel) {
        wx.showToast({
          title: '请填写送货人电话',
          icon: "none"
        })
        return;
      }
      this.setData({
        'sendFormData.expressName': '',
        'sendFormData.expressNumber': "",
        'sendFormData.expressCode': "",
      })
      if (this.data.isSendStatus == 0) {
        debounce(this.sureSendOrder)
      } else {
        debounce(this.sureChangeOrder)
      }
    }
    if (this.data.sendFormData.type == 3) {
      //虚拟发货
      if (this.data.isSendStatus == 0) {
        debounce(this.sureSendOrder)
      } else {
        debounce(this.sureChangeOrder)
      }
    }
  },
  //确认发货
  sureSendOrder() {
    wx.showLoading();
    let subData = {};
    if (this.data.sendFormData.type == 3) {
      subData = {
        "type": "3",
        "expressRecordType": "3",
        "expressCode": "",
        "company": "",
        "deliveryName": "",
        "deliveryTel": "",
        "expressName": "",
        "expressNumber": "",
        "expressTempId": "",
        "toAddr": "陕西省西安市曲江新区",
        "toName": "曲江旺座",
        "toTel": "18710383544",
        "orderNo": this.data.sendFormData.orderNo,
        "shipment": {
          "sendRealName": "",
          "sendPhone": "",
          "sendAddress": "",
          "kuaidicom": "",
          "serviceType": "",
          "pickupStartTime": "",
          "pickupEndTime": "",
          "tempid": "",
          "dayType": 1
        }
      }

    } else {
      subData = this.data.sendFormData
    }

    orderSend(subData).then(res => {
      wx.hideLoading()
      if (res.code == 200) {
        wx.showToast({
          title: "发货成功",
          icon: "success"
        })
        //currentOrderIndex
        let orderData = this.data.orderList[this.data.currentOrderIndex];
        orderData.status = 1;
        let item = 'orderList[' + this.data.currentOrderIndex + ']';
        this.setData({
          [item]: orderData,
          showSendPop: false,
        })

      }
    }).catch(err => {
      wx.hideLoading()
      wx.showToast({
        title: err || '发货失败',
        icon: "none"
      })
      console.error("JJLog:orderSend", err)
    })
  },
  // 确认修改:
  sureChangeOrder(){
    wx.showLoading();
    let subData = {};
    if (this.data.sendFormData.type == 3) {
      subData = {
        "type": "3",
        "expressRecordType": "3",
        "expressCode": "",
        "company": "",
        "deliveryName": "",
        "deliveryTel": "",
        "expressName": "",
        "expressNumber": "",
        "expressTempId": "",
        "toAddr": "陕西省西安市曲江新区",
        "toName": "曲江旺座",
        "toTel": "18710383544",
        "orderNo": this.data.sendFormData.orderNo,
        "shipment": {
          "sendRealName": "",
          "sendPhone": "",
          "sendAddress": "",
          "kuaidicom": "",
          "serviceType": "",
          "pickupStartTime": "",
          "pickupEndTime": "",
          "tempid": "",
          "dayType": 1
        }
      }

    } else {
      subData = this.data.sendFormData
    }

    orderSendUpdate(subData).then(res => {
      wx.hideLoading()
      if (res.code == 200) {
        wx.showToast({
          title: "修改成功",
          icon: "success"
        })
        //currentOrderIndex
        let orderData = this.data.orderList[this.data.currentOrderIndex];
        // orderData.status = 1;
        let item = 'orderList[' + this.data.currentOrderIndex + ']';
        this.setData({
          [item]: orderData,
          showSendPop: false,
        })

      }
    }).catch(err => {
      wx.hideLoading()
      wx.showToast({
        title: err || '发货失败',
        icon: "none"
      })
      console.error("JJLog:orderSend", err)
    })
  },
  copyReceiveAction(e){
    if(this.data.currentOrderData && this.data.currentOrderData.orderId == e.detail.orderId){
      //点击到同一个了，就直接复制：
      this.copyReceiveInfo();
      return;
    }
    this.queryOrderDetail(e.detail.orderId,'copy');
  },
  queryOrderDetail(orderId,type) {
    wx.showLoading();
    queryOrderDetail(orderId).then(res => {
      console.log(res)
      wx.hideLoading()
      if (res.code == 200) {
        this.setData({
         currentOrderData:res.data,
        })
        if(type == 'show'){
          this.setData({
            showReceivePop:true,
          })
        }else{
          this.copyReceiveInfo();
        }

      }
    }).catch(err => {
      wx.hideLoading()
      console.error("JJLog:queryOrderDetail", err)
      wx.showToast({
        title: err || '查询失败',
        icon: "none"
      })
    })
  },
  playPhoneAction(){
    let phone = this.data.currentOrderData.userPhone
    this.setData({
      showReceivePop:false
    })
    wx.makePhoneCall({
      phoneNumber: phone,
      fail:err =>{

      }
    })
  },
  //一键复制信息
  copyReceiveInfo(){
    let item = this.data.currentOrderData;
    let copyText = "";
    copyText = "姓名：" + item.realName + "\n";
    copyText = copyText + '手机号：' + item.userPhone + "\n";
    copyText = copyText + '地址：' + item.userAddress + '\n';
    wx.setClipboardData({
      data: copyText,
      success: (res) => {
        wx.getClipboardData({
          success: (res) => {
            this.setData({
              showReceivePop:false
            })
            wx.showToast({
              title: '复制信息成功'
            })
          },
          fail: (err) => {
            wx.showToast({
              title: '复制失败',
              icon: "none"
            })
          }
        })
      }
    })
  },

})